package com.roc.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.bean.TransLimitBean;
import com.roc.dao.DaoException;
import com.roc.dao.IBaseDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.pojo.Operators;
import com.roc.service.ServiceException;
import com.roc.service.riskRule.ITransLimitService;
import com.roc.util.Constance;
import com.roc.util.constant.SysLogType;
@Service
@Transactional
public class TransLimitServiceImpl implements ITransLimitService {
	static Logger logger=Logger.getLogger(TransLimitServiceImpl.class);
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	@Autowired
	private IBaseDao baseDao;
	/**
	 * 批量生成风控交易限制规则（新）
	 *//*
	@Override
	public Map<String, Object> addNewRiskRuleToMcht(TransLimitBean bean,Operators op)
			throws ServiceException {
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try {
		String msg="";
		String flag=checkFlag(bean);
		if(!"0".equals(flag))
		{
			msg="已存在此条风控规则";
			resultMap.put("result", msg);
			logger.info(msg);
			return resultMap;
		}
		//保存机构号，商户号，终端号
		String sql= " insert into APSTFR.TBL_MGM_RISK_RULE     \n "     
						+"  (risk_level,                        \n"         //风控等级
						+"   risk_ins_cd,                       \n"         //机构号  
						+"   risk_mcht_cd,                      \n"         //商户号 
						+"   risk_term_cd,                      \n"         //终端号 
						+"   risk_trans_type,       			\n"			//交易种类            
						+"   risk_info_type,        			\n"			//风控对象             
						+"   risk_num_cycle,        			\n"			//风控周期             
						+"   risk_key_type,         			\n"			//特使类型              
						+"   risk_num_type,         			\n"		    //计算方法              
						+"   risk_num_unite, 					\n"			//单位类型             
						+"   risk_num_vaule, 					\n"			//数值                 
						+"   risk_check_time,					\n"		    //检查时间            
						+"   risk_write_time,					\n"		    //记录时间            
						+"   risk_use              				\n"			//0否1是 是否启用             
						+"   )                                  \n"   
						+"  select 'V',                         \n"         //风控等级 
						+"         ?  risk_ins_cd, 				\n"			//机构号         
						+"         ?  risk_mcht_cd,				\n"			//商户号        
						+"         ?  risk_term_cd,				\n"			//终端号        
						+"         tr.risk_trans_type,			\n"			//交易种类   
						+"         tr.risk_info_type, 			\n"			//风控对象    
						+"         tr.risk_num_cycle, 			\n"			//风控周期    
						+"         tr.risk_key_type, 			\n"			//特使类型     
						+"         tr.risk_num_type, 			\n"			//计算方法     
						+"         tr.risk_num_unite,			\n"			//单位类型    
						+"         tr.risk_num_vaule, 			\n"			//数值        
						+"         tr.risk_check_time,			\n"			//检查时间   
						+"         tr.risk_write_time,			\n"			//记录时间   
						+"         tr.risk_use                  \n"         //0否1是 是否启用    
						+"    from APSTFR.TBL_MGM_RISK_RULE tr  \n"   
						+"   where tr.risk_level = 'F'          \n"  
						+"    AND tr.RISK_USE <> '0'            "  ;
		List<Object> parmas=new ArrayList<Object>();
		parmas.add(bean.getInCd());
		parmas.add(bean.getMchtCd());
		parmas.add(bean.getTermCd());
		int count=sqlBaseDao.deleteBySql(sql, parmas);
		if(count>0)
		{
			msg="添加规则成功";
			logger.info(msg);
			baseDao.addSyslog(SysLogType.RISK_RULE_ADD.getCode(), SysLogType.RISK_RULE_ADD.getName(), op.getAccountNo(),op.getAccountNo()+"为机构号【"+bean.getInCd()+"】商户号【"+bean.getMchtCd()+"】终端号【"+bean.getTermCd()+"】添加风控规则成功");
		}
		} catch (DaoException e) {
			logger.debug(e.getMessage(),e);
			throw new ServiceException("添加规则失败");
		}
		return resultMap;
	}*/
	@Override
	public Map<String, Object> addNewRiskRuleToMcht(TransLimitBean bean,Operators op)
			throws ServiceException {
		Map<String, Object> resultMap=new HashMap<String, Object>();
		try {
		String msg="";
		TransLimitBean checkBean=findBean(bean);
		if(checkBean!=null)
		{
			msg="已存在此条风控规则";
			resultMap.put("result", msg);
			logger.info(msg);
			return resultMap;
		}
		TransLimitBean beanExplame=findExplameByBean(bean);//找到对应的风控规则模板
		if(beanExplame==null)
		{
			msg="不存在此风控规则模板";
			resultMap.put("result", msg);
			logger.info(msg);
			return resultMap;
		}
		//更正机构号，商户号，终端号
		String sql=" INSERT INTO APSTFR.TBL_MGM_RISK_RULE(RISK_INS_CD,RISK_MCHT_CD,RISK_TERM_CD,RISK_TRANS_TYPE,"
				+ " RISK_INFO_TYPE,RISK_NUM_CYCLE,RISK_KEY_TYPE,RISK_NUM_TYPE,RISK_NUM_UNITE,RISK_NUM_VAULE,"
				+ " RISK_CHECK_TIME,RISK_WRITE_TIME,RISK_USE) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
		List<Object> parmas=new ArrayList<Object>();
		parmas.add(bean.getInCd());
		parmas.add(bean.getMchtCd());
		parmas.add(bean.getTermCd());
		parmas.add(bean.getTransType());
		parmas.add(bean.getRiskInfo());
		parmas.add(bean.getRiskCycle());
		parmas.add(bean.getRiskKey());
		parmas.add(bean.getRiskMethod());
		parmas.add(bean.getUnite());
		parmas.add(bean.getValueMax());
		parmas.add(beanExplame.getCheckTime());
		parmas.add(beanExplame.getWriteTime());
		parmas.add(bean.getStatus());
			int count=sqlBaseDao.deleteBySql(sql, parmas);
			if(count>0)
			{
				msg="添加规则成功";
				logger.info(msg);
				baseDao.addSyslog(SysLogType.RISK_RULE_ADD.getCode(), SysLogType.RISK_RULE_ADD.getName(), op.getAccountNo(),op.getAccountNo()+"为机构号【"+bean.getInCd()+"】商户号【"+bean.getMchtCd()+"】终端号【"+bean.getTermCd()+"】添加风控规则成功");
			}
		} catch (DaoException e) {
			logger.debug(e.getMessage(),e);
			throw new ServiceException("添加规则失败");
		}
		return resultMap;
	}

	@Override
	public int updateRiskRule(TransLimitBean bean,Operators op) throws ServiceException {
		int count=0;
		try {
		String sql=" UPDATE APSTFR.TBL_MGM_RISK_RULE SET RISK_NUM_VAULE=?,RISK_USE=? WHERE RISK_INS_CD=?"
				+ " AND RISK_MCHT_CD=? AND RISK_TERM_CD=? AND RISK_TRANS_TYPE=? AND RISK_INFO_TYPE=? "
				+ " AND RISK_NUM_CYCLE=? AND RISK_KEY_TYPE=? AND RISK_NUM_TYPE=? AND RISK_NUM_UNITE=? ";
		List<Object> parmas=new ArrayList<Object>();
		parmas.add(bean.getValueMax());
		parmas.add(bean.getStatus());
		parmas.add(bean.getInCd());
		parmas.add(bean.getMchtCd());
		parmas.add(bean.getTermCd());
		parmas.add(bean.getTransType());
		parmas.add(bean.getRiskInfo());
		parmas.add(bean.getRiskCycle());
		parmas.add(bean.getRiskKey());
		parmas.add(bean.getRiskMethod());
		parmas.add(bean.getUnite());
		count=sqlBaseDao.deleteBySql(sql, parmas);
		if(count>0){
			logger.info("修改风控规则成功!");
			baseDao.addSyslog(SysLogType.RISK_RULE_UPDATE.getCode(), SysLogType.RISK_RULE_UPDATE.getName(), op.getAccountNo(),op.getAccountNo()+"为机构号【"+bean.getInCd()+"】商户号【"+bean.getMchtCd()+"】终端号【"+bean.getTermCd()+"】修改风控规则成功");
			}
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public TransLimitBean findBean(TransLimitBean bean)
			throws ServiceException {
		TransLimitBean beans=null;
		try {
		String sql="SELECT T.RISK_INS_CD,T.RISK_MCHT_CD,T.RISK_TERM_CD,T.RISK_TRANS_TYPE,T.RISK_INFO_TYPE, "
				+ " T.RISK_NUM_CYCLE,T.RISK_KEY_TYPE,T.RISK_NUM_TYPE,T.RISK_NUM_UNITE,T.RISK_NUM_VAULE, "
				+ " T.RISK_CHECK_TIME,T.RISK_WRITE_TIME,T.RISK_USE FROM APSTFR.TBL_MGM_RISK_RULE T "
				+ " WHERE T.RISK_INS_CD=? AND T.RISK_MCHT_CD=? AND T.RISK_TERM_CD=? AND T.RISK_TRANS_TYPE=? "
				+ " AND T.RISK_INFO_TYPE=? AND T.RISK_NUM_CYCLE=? AND T.RISK_KEY_TYPE=? "
				+ " AND T.RISK_NUM_TYPE=? AND T.RISK_NUM_UNITE=? ";
		Object[] parmas=new Object[9];
		parmas[0]=bean.getInCd();
		parmas[1]=bean.getMchtCd();
		parmas[2]=bean.getTermCd();
		parmas[3]=bean.getTransType();
		parmas[4]=bean.getRiskInfo();
		parmas[5]=bean.getRiskCycle();
		parmas[6]=bean.getRiskKey();
		parmas[7]=bean.getRiskMethod();
		parmas[8]=bean.getUnite();
		Object object=sqlBaseDao.findObj(sql, parmas);
		if(object!=null){
			Object[] obj=(Object[]) object;
			beans=new TransLimitBean();
			beans.setInCd(Constance.Null2EmptyTrim(obj[0]));
			beans.setMchtCd(Constance.Null2EmptyTrim(obj[1]));
			beans.setTermCd(Constance.Null2EmptyTrim(obj[2]));
			beans.setTransType(Constance.Null2EmptyTrim(obj[3]));
			beans.setRiskInfo(Constance.Null2EmptyTrim(obj[4]));
			beans.setRiskCycle(Constance.Null2EmptyTrim(obj[5]));
			beans.setRiskKey(Constance.Null2EmptyTrim(obj[6]));
			beans.setRiskMethod(Constance.Null2EmptyTrim(obj[7]));
			beans.setUnite(Constance.Null2EmptyTrim(obj[8]));
			beans.setValueMax(Constance.Null2EmptyTrim(obj[9]));
			beans.setCheckTime(Constance.Null2EmptyTrim(obj[10]));
			beans.setWriteTime(Constance.Null2EmptyTrim(obj[11]));
			beans.setStatus(Constance.Null2EmptyTrim(obj[12]));
			}
		} catch (DaoException e) {
			logger.info("查询风控规则失败!!!");
			e.printStackTrace();
		}
		return beans;
	}
	
	@Override
	public String checkFlag(TransLimitBean bean)
			throws ServiceException {
		String flag=null;
		try {
		String sql="select count(1) from APSTFR.TBL_MGM_RISK_RULE r where r.risk_mcht_cd = ? and r.RISK_USE <> '0' ";
		Object[] parmas=new Object[1];
		parmas[0]=bean.getMchtCd();
		Object object=sqlBaseDao.findObj(sql, parmas);
		if(object!=null){
			flag=object.toString();
		}
		} catch (DaoException e) {
			logger.info("查询风控规则失败!!!");
			e.printStackTrace();
		}
		return flag;
	}
	protected TransLimitBean findExplameByBean(TransLimitBean bean)
	{
		TransLimitBean beans=null;
		String sql="SELECT T.RISK_INS_CD,T.RISK_MCHT_CD,T.RISK_TERM_CD,T.RISK_TRANS_TYPE,T.RISK_INFO_TYPE, "
				+ " T.RISK_NUM_CYCLE,T.RISK_KEY_TYPE,T.RISK_NUM_TYPE,T.RISK_NUM_UNITE,T.RISK_NUM_VAULE, "
				+ " T.RISK_CHECK_TIME,T.RISK_WRITE_TIME,T.RISK_USE FROM APSTFR.TBL_MGM_RISK_RULE T "
				+ " WHERE T.RISK_INS_CD='*' AND T.RISK_MCHT_CD='*' AND T.RISK_TERM_CD='*' AND T.RISK_TRANS_TYPE=? "
				+ " AND T.RISK_INFO_TYPE=? AND T.RISK_NUM_CYCLE=? AND T.RISK_KEY_TYPE=? "
				+ " AND T.RISK_NUM_TYPE=? AND T.RISK_NUM_UNITE=? ";
		Object[] parmas=new Object[6];
		parmas[0]=bean.getTransType();
		parmas[1]=bean.getRiskInfo();
		parmas[2]=bean.getRiskCycle();
		parmas[3]=bean.getRiskKey();
		parmas[4]=bean.getRiskMethod();
		parmas[5]=bean.getUnite();
		try {
			Object obj=sqlBaseDao.findObj(sql, parmas);
			if(obj!=null)
			{
				Object[] object=(Object[]) obj;
				beans=new TransLimitBean();
				beans.setCheckTime(Constance.Null2EmptyTrim(object[10]));
				beans.setWriteTime(Constance.Null2EmptyTrim(object[11]));
			}
		} catch (DaoException e) {
			logger.info("校验风控规则模板失败!!!");
			e.printStackTrace();
		}
		return beans;
		
	}
}
